package cn.edu.zafu.bigdata.fui;

import java.util.Random;
import java.util.Scanner;

public class GuessNumberGame {
    private int maxAttempts; // 最大尝试次数
    private int numberToGuess; // 要猜测的数字
    private Random random; // 用于生成随机数
    private Scanner scanner; // 用于读取用户输入

    public GuessNumberGame(int maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.random = new Random();
        this.scanner = new Scanner(System.in);
    }

    // 开始游戏的方法
    public void startGame() {
        boolean playAgain = true;

        while (playAgain) {
            numberToGuess = random.nextInt(100) + 1; // 生成1到100之间的随机数
            int attempts = 0;
            boolean guessedCorrectly = false;

            System.out.println("猜数字游戏开始！你有 " + maxAttempts + " 次机会猜对数字。");

            while (attempts < maxAttempts && !guessedCorrectly) {
                System.out.print("请输入你猜的数字（1-100）：");
                int guess = scanner.nextInt();
                attempts++;

                if (guess < numberToGuess) {
                    System.out.println("小了！");
                } else if (guess > numberToGuess) {
                    System.out.println("大了！");
                } else {
                    System.out.println("恭喜你，猜对了！你用了 " + attempts + " 次。");
                    guessedCorrectly = true;
                }
            }

            if (!guessedCorrectly) {
                System.out.println("很遗憾，你没有在 " + maxAttempts + " 次内猜对。正确的数字是 " + numberToGuess + "。");
            }

            System.out.print("重新开始(yes/no)：");
            String answer = scanner.next().trim().toLowerCase();
            playAgain = answer.equals("yes");
        }

        scanner.close();
    }

    public static void main(String[] args) {
        GuessNumberGame game = new GuessNumberGame(10);
        game.startGame();
    }
}